﻿using System;
using UnityEngine;
using UnityEditor;

namespace TC
{
    // TODO 改为单例类
    class BezierUtil
    {
        private static float normalLineWidth = 3;
        private static float activeLineWidth = 8;
        private static float bezierCalcuNumber = 100;
        private static float extraLineDistance = 1;


        private static float GetTangentRatio(Vector2 startPos, Vector2 endPos)
        {
            var width = Math.Abs(endPos.x - startPos.x);
            var height = Math.Abs(endPos.y - startPos.y);
            return height * width / (height + width) * 1.5f;
        }

        public static void DrawBezier(Vector2 startPos, Vector2 endPos, Color color, bool isActive = false)
        {
            var ratio = GetTangentRatio(startPos, endPos);
            //var color = isActive ? StyleProvider.ActiveConnectColor : StyleProvider.DefaultConnectColor;
            var lineWidth = isActive ? activeLineWidth : normalLineWidth;
            Handles.DrawBezier(startPos, endPos, startPos + Vector2.right * ratio, endPos + Vector2.left * ratio, color, null, lineWidth);
        }

        private static Vector2 GetPosAlongBezier(Vector2 startPos, Vector2 endPos, Vector2 startTangent, Vector2 endTangent, float t)
        {
            float tt = t * t;
            float ttt = t * tt;
            float u = 1 - t;
            float uu = (1 - t) * (1 - t);
            float uuu = u * uu;
            return uuu * startPos + 3 * uu * t * startTangent + 3 * u * tt * endTangent + ttt * endPos;
        }

        public static bool Contains(Vector2 startPos, Vector2 endPos, bool isActive, Vector2 pos)
        {
            var ratio = GetTangentRatio(startPos, endPos);
            Vector2 startTangent = startPos + Vector2.right * ratio;
            Vector2 endTangent = endPos + Vector2.left * ratio;
            float validRadius = extraLineDistance + (isActive ? activeLineWidth : normalLineWidth);
            float validRadiusSquare = validRadius * validRadius;
            for (int i = 3; i < bezierCalcuNumber - 3; i++)
            {
                var linePos = GetPosAlongBezier(startPos, endPos, startTangent, endTangent, i/bezierCalcuNumber);
                var distance = pos - linePos;
                var distanceSquare = distance.x * distance.x + distance.y * distance.y;
                if (distanceSquare <= validRadiusSquare) { return true; }
            }
            return false;
        }
    }
}
